package cn.lbz.Register;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.swing.*;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.Serial;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

public class RegisterServlet extends HttpServlet {
    @Serial
    private static final long serialVersionUID = -9082295726415709189L;

    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
        boolean b;
        String newuser=request.getParameter("newuser");
        String newpass=request.getParameter("newpass");
        b=userregister(newuser,newpass);
        if(b){
            response.sendRedirect("login.html");
            System.out.println("注册成功");
            JOptionPane.showMessageDialog(null, "注册成功！");
        }
        else{
            response.sendRedirect("register.html");
            System.out.println("注册失败");
            JOptionPane.showMessageDialog(null, "注册失败！\n该用户已存在");}
    }
    private static final String DB_DRIVER = "com.mysql.cj.jdbc.Driver";
    private static final String DB_URL    = "jdbc:mysql://127.0.0.1:3306/user";
    private static final String DB_USER   = "root";
    private static final String DB_PASS   = "20020111Zhao";

    private boolean userregister(String user,String password){
        boolean b = false;
        String sql = "select * from user where uname='"+user+"'";

        try{
            Class.forName(DB_DRIVER);
            Connection conn = DriverManager.getConnection(DB_URL,DB_USER,DB_PASS);
            Statement stm = conn.createStatement();
            ResultSet rs = stm.executeQuery(sql);
            System.out.println(sql);

            if(!rs.next()){
                sql = "insert into user(uname,password) values('"+user+"','"+password+"')";
                stm.execute(sql);
                b = true;
            }
            rs.close();
            stm.close();
            conn.close();
        }catch (Exception e) {
            e.printStackTrace();
        }
        return b;
    }
}


